﻿<template>
  <l-layout class="l-tab-page" v-if="!lr_loadPage">
    <template #left>
      <l-panel :title="$t('租户组')" style="padding-right: 0">
        <el-tree
          class="learun-tree"
          v-loading="treeLoading"
          :data="treeData"
          default-expand-all
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
        >
          <span class="lr-tree-node" slot-scope="{ node }">
            {{ $t(node.label) }}
          </span>
        </el-tree>
      </l-panel>
    </template>

    <l-panel style="padding-left: 0">
      <template #toolLeft>
        <l-query2
          :items="queryItems"
          :formData="queryData"
          :loading="tableLoading"
          @search="handleSearch"
        >
          <template #f_Code>
            <el-input v-model="queryData.f_Code" :placeholder="$t('please enter')" />
          </template>
          <template #f_Name>
            <el-input v-model="queryData.f_Name" :placeholder="$t('please enter')" />
          </template>
          <template #f_Company>
            <el-input
              v-model="queryData.f_Company"
              :placeholder="$t('please enter')"
            />
          </template>
          <template #f_State>
            <l-select v-model="queryData.f_State" :options="optionsState" />
          </template>
        </l-query2>
      </template>
      <template #toolRight>
        <l-tool-btns
          @click="handleAdd()"
        >
          <l-excel-btns></l-excel-btns>
          <el-button-group>
            <el-button size="mini" @click="HandleOpenTaskForm">{{
              $t("查看租户任务")
            }}</el-button>
          </el-button-group>
        </l-tool-btns>
      </template>
      <l-table
        ref="mainTable"
        :loading="tableLoading"
        :columns="lr_getPageColumns(columns)"
        :dataSource="tableData"
        :isPage="true"
        :pageTotal="tableTotal"
        :tablePage.sync="tableCurrentPage"
        @loadPageData="turnTablePage"
      >
        <template v-slot:f_EnabledMark="scope">
          <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="scope.row.f_EnabledMark"
            @change="handleEnableChange(scope.row)"
          >
          </el-switch>
        </template>
        <template v-slot:f_IsUnUsed="scope">
          <el-switch
            disabled
            :active-value="1"
            :inactive-value="0"
            v-model="scope.row.f_IsUnUsed"
          >
          </el-switch>
        </template>
        <l-table-btns
          :btns="tableBtns"
          @click="lr_handleTableBtnClick"
        ></l-table-btns>
      </l-table>
    </l-panel>

    <!--表单-->
    <l-dialog
      :title="$t(formTitle)"
      :visible.sync="formVisible"
      :height="600"
      :width="800"
      @ok="handleSave"
      @close="handleCloseForm"
      @opened="handleOpenedForm"
    >
      <my-form ref="form"></my-form>
    </l-dialog>

    <l-drawer
      :title="`${$t('查看同步日志')}-${name}`"
      :visible.sync="logVisible"
      :showOk="false"
      :showClose="false"
      :width="800"
      @close="handleCloseLogForm"
      @opened="handleOpenedLogForm"
    >
      <my-logform ref="logform"></my-logform>
    </l-drawer>

    <l-drawer
      :title="`${$t('查看任务')}`"
      :visible.sync="taskVisible"
      :showOk="false"
      :showClose="false"
      :width="800"
      @close="handleCloseTaskForm"
      @opened="handleOpenedTaskForm"
    >
      <my-task-form ref="taskform" />
    </l-drawer>
  </l-layout>
</template>

<script>
import MyForm from "./form";
import MyLogform from "./logform";
import MyTaskForm from "./taskForm";
const api = window.$api.sass.tenant;

export default {
  components: {
    MyForm,
    MyLogform,
    MyTaskForm,
  },
  data() {
    return {
      lr_isPage: true,
      moduleCode: "sass_tenant",
      // 左侧树形数据参数
      treeLoading: false,
      treeCategory: "",

      // query参数
      queryData: {
        f_Code: "",
        f_Name: "",
        f_Company: "",
        f_State: null,
      },

      queryItems: [
        { label: this.$t("编码"), prop: "f_Code" },
        { label: this.$t("名称"), prop: "f_Name" },
        { label: this.$t("公司"), prop: "f_Company" },
        { label: this.$t("状态"), prop: "f_State" },
      ],

      // 表格参数
      tableLoading: false,
      tableData: [],
      tableTotal: 0,
      tableCurrentPage: 1,
      tablePageSize: 50,
      columns: [
        {
          label: "编码",
          prop: "f_Code",
          width: 120,
          align: "left",
          dataType: "encode",
        },
        { label: "名称", prop: "f_Name", minWidth: 120, align: "left" },
        { label: "公司", prop: "f_Company", minWidth: 120, align: "left" },
        { label: "有效", prop: "f_EnabledMark", width: 80, align: "center" },
        { label: "闲置", prop: "f_IsUnUsed", width: 80, align: "center" },
        {
          label: "同步状态",
          prop: "f_State",
          width: 100,
          align: "center",
          formatter: function ({ cellValue }) {
            switch (cellValue) {
              case 100:
                return "等待";
              case 99:
                return "异常";
              case 0:
                return "完成";
              case 1:
                return "同步表结构";
              case 2:
                return "同步数据";
              case 3:
                return "创建账号";
              case 4:
                return "同步菜单";
            }
          },
        },
      ],

      optionsState: [
        { value: 0, label: this.$t("完成") },
        { value: 1, label: this.$t("同步表结构") },
        { value: 2, label: this.$t("同步数据") },
        { value: 3, label: this.$t("创建账号") },
        { value: 4, label: this.$t("同步菜单") },
        { value: 99, label: this.$t("异常") },
        { value: 100, label: this.$t("等待") },
      ],
      tableBtns: [
        { prop: "Update", label: this.$t("同步") },
        { prop: "Log", label: this.$t("日志") },
        { prop: "Edit", label: this.$t("Edit") },
        { prop: "Delete", label: this.$t("Delete") },
        { prop: "Copy", label: this.$t("复制") },
        { prop: "Reset", label: this.$t("Reset管理password") },
      ],

      // 表单参数
      formVisible: false,
      formTitle: "",
      formEditRow: null,
      formEdit: false,

      name: "",
      logVisible: false,

      taskVisible: false,
    };
  },
  computed: {
    // 左侧树形数据参数
    treeData() {
      return this.lr_DataSourceTree(
        this.lr_dataSourceData["tenantGroup"],
        "f_id",
        "f_id",
        "f_id",
        "f_name"
      );
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.lr_loadDataSourceData("tenantGroup", false);
      this.loadTableData();
    },
    handleNodeClick(node) {
      this.treeCategory = node.value;
      this.loadTableData(true);
    },

    handleSearch() {
      this.loadTableData();
    },
    turnTablePage({ rows }) {
      this.tablePageSize = rows;
      this.loadTableData(true);
    },
    async loadTableData(isNotFirst) {
      if (!isNotFirst) {
        this.tableCurrentPage = 1;
      }
      this.tableLoading = true;
      let queryData = this.$deepClone(this.queryData);

      queryData.rows = this.tablePageSize;
      queryData.page = this.tableCurrentPage;
      queryData.sidx = "F_IsUnUsed,F_ModifyDate DESC,F_CreateDate DESC";
      queryData.f_TenantGroupId = this.treeCategory;
      let data = await this.$awaitWraper(api.getPage(queryData));
      if (data != null) {
        this.tableData = data.rows;
        this.tableTotal = data.records;
      } else {
        this.tableData = [];
      }
      this.tableLoading = false;
    },

    handleAdd() {
      this.formEdit = false;
      this.handleShowForm("Add租户");
    },
    handleEdit($index, row) {
      if (row.f_State != 0) {
        this.$message({
          type: "warning",
          message: this.$t("当前不是空闲状态,无法Edit!"),
        });
        return;
      }
      this.formEdit = true;
      this.formEditRow = row;
      this.handleShowForm("Edit租户");
    },
    handleDelete($index, row) {
      /*if (row.f_State != 0 && row.f_State != 99) {
        this.$message({
          type: "warning",
          message: this.$t("当前不是空闲状态,无法Delete!"),
        });
        return;
      }*/

      this.$confirm(
        this.$t("This operation will permanently delete the data. Do you want to continue?"),
        this.$t("Tips"),
        {
          confirmButtonText: this.$t("confirm"),
          cancelButtonText: this.$t("cancel"),
          type: "warning",
        }
      )
        .then(async () => {
          this.tableData.splice($index, 1);
          this.tableTotal--;
          await api.remove(row.f_Id);
          this.$message({
            type: "success",
            message: this.$t("Delete  success"),
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t("Delete has been canceled!"),
          });
        });
    },
    handleUpdate($index, row) {
      if (row.f_State != 0 && row.f_State != 99) {
        this.$message({
          type: "warning",
          message: this.$t("当前不是空闲状态,无法同步!"),
        });
      } else {
        this.$confirm(this.$t("是否同步数据?"), this.$t("Tips"), {
          confirmButtonText: this.$t("confirm"),
          cancelButtonText: this.$t("cancel"),
          type: "warning",
        })
          .then(async () => {
            await api.updateTask(row.f_Id);
            this.$message({
              type: "success",
              message: this.$t("提交成功!"),
            });
            this.loadTableData();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: this.$t("已cancel同步!"),
            });
          });
      }
    },
    handleLog($index, row) {
      this.name = row.f_Name;
      this.formEditRow = row;
      this.logVisible = true;
    },

    handleCopy($index, row) {
      if (row.f_State != 0) {
        this.$message({
          type: "warning",
          message: this.$t("当前不是空闲状态,无法同步!"),
        });
      } else {
        this.$confirm(this.$t("是否复制?"), this.$t("Tips"), {
          confirmButtonText: this.$t("confirm"),
          cancelButtonText: this.$t("cancel"),
          type: "warning",
        })
          .then(async () => {
            await api.copy(row.f_Id);
            this.$message({
              type: "success",
              message: this.$t("复制成功!"),
            });
            this.loadTableData();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: this.$t("已cancel复制!"),
            });
          });
      }
    },

    async handleSave(showLoading, hideLoading) {
      showLoading("saving data...");
      if (await this.$refs.form.validateForm()) {
        const res = await this.$refs.form.saveForm({
          keyValue: this.formEdit ? this.formEditRow.f_Id : "",
          isEdit: this.formEdit,
        });
        if (res) {
          const msg = this.formEdit ? this.$t("更新成功!") : this.$t("Add成功!");
          this.$message({
            type: "success",
            message: this.$t(msg),
          });
          this.loadTableData();
          this.formVisible = false;
        }
      }
      hideLoading();
    },

    handleReset($index, row) {
      if (row.f_State != 0) {
        this.$message({
          type: "warning",
          message: this.$t("当前不是空闲状态,无法Reset!"),
        });
        return;
      }

      this.$confirm(
        this.$t("此操作将Reset租户管理员password, 是否继续?"),
        this.$t("Tips"),
        {
          confirmButtonText: this.$t("confirm"),
          cancelButtonText: this.$t("cancel"),
          type: "warning",
        }
      )
        .then(async () => {
          await api.resetAdmin(row.f_Id);
          this.$message({
            type: "success",
            message: this.$t("Reset成功!"),
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t("Delete has been canceled!"),
          });
        });
    },

    handleShowForm(text) {
      this.formTitle = text;
      this.formVisible = true;
    },
    async handleOpenedForm(showLoading, hideLoading) {
      if (this.formEdit) {
        showLoading("Loading data...");
        await this.$refs.form.loadFormData({ keyValue: this.formEditRow.f_Id });
        hideLoading();
      }
    },
    handleCloseForm() {
      this.$refs.form.resetForm();
    },

    async handleEnableChange(row) {
      const res = await this.$awaitWraper(api.update(row.f_Id, row));
      if (res) {
        this.$message({
          type: "success",
          message: this.$t("更新成功!"),
        });
      }
    },

    handleCloseLogForm() {
      this.$refs.logform.resetForm();
    },
    handleOpenedLogForm() {
      this.$refs.logform.init(this.formEditRow.f_Id);
    },

    HandleOpenTaskForm() {
      this.taskVisible = true;
    },
    handleCloseTaskForm() {
      this.$refs.taskform.resetForm();
    },
    handleOpenedTaskForm() {
      this.$refs.taskform.init();
    },
  },
};
</script>
